package ArrayListTest;

import java.util.Arrays;

public class MyArrayList<T> {
    private T[] data;//存储数组
    private int size;//量


    public MyArrayList() {
        this(10);
    }

    public MyArrayList(int initialSize) {
        data = (T[]) new Object[initialSize];
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder("[");
        for (int i = 0; i < size; i++) {
            s.append(data[i]);
            if (i < size - 1) {
                s.append(", ");
            }
        }
        s.append("]");
        return s.toString();
    }

    public T[] getData() {
        return data;
    }

    public void setData(T[] data) {
        this.data = data;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    // 添加
    public void add(T t) {
        if (size == data.length) {
            data= Arrays.copyOf(data, data.length*2);
        }
        data[size++] = t;
    }

    // 获取指定索引处的元素
    public T get(int index) {
        checkIndex(index);
        return (T) data[index];
    }

    // 修改
    public void set(int index, T t) {
        checkIndex(index);
        data[index] = t;
    }

    public T remove(int index){
        checkIndex(index);
        T t=data[index];
        for(int i=index;i<size-1;i++){
            data[i]=data[i+1];
        }
        size--;
        return t;
    }

    //检查索引是否合法
    private void checkIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }
    }
}
